<template>
    <div id="apntDiv" class="page-content-text">
        <header-layout isShowBack :title="$t('netWork.apnSettings.apnSettingTitle')" @BackClick="jumpBackUrl"></header-layout>
        <div id="apnBox" class="page-content-normal">
             <!-- APN列表表格 -->
            <table border="1" style="width: 100%" v-if="Array.isArray(formatList) && formatList.length">
                <tr class="table_title">
                    <th style="width: 10%">{{ $t('netWork.vpnSetting.profileTitle') }}</th>
                    <th style="width: 10%">{{ $t('netWork.apnSettings.Default') }}</th>
                    <th style="width: 10%">{{ $t('netWork.apnSettings.Status') }}</th>
                    <th style="width: 22%">{{ $t('netWork.apnSettings.apnAPN') }}</th>
                    <th style="width: 22%">{{ $t('common.username') }}</th>
                    <th style="width: 6%"></th>
                </tr>
                <tr :class="index % 2 === 0 ? 'table3_font' : 'table3_color'" v-for="(item, index) in formatList" :key="index">
                    <td>{{ item.id}}</td>
                    <td>
                        <el-checkbox :id="`checkbox_${index + 1}`" v-model="item.isChecked" type="checkbox" class="checkbox" :disabled="item.isChecked || !item.switchStatus" @change="changeDefault(index)"></el-checkbox>
                    </td>
                    <td>
                        <span :id="`switch_${index + 1}`">{{ item.switchStatus ? $t('common.onLabel') : $t('common.offLabel') }}</span>
                    </td>
                    <td class="clamp-ellipsis">
                        <span :id="`name_${index + 1}`">{{ item.label }}</span>
                    </td>
                    <td class="clamp-ellipsis">
                        <span :id="`username_${index + 1}`">{{ item.username }}</span>
                    </td>
                    <td>
                        <el-link @click="editDialog(item)" :id="`editButton_${index + 1}`" class="apnEdit" :underline="false">{{ $t('common.editButton') }}</el-link>
                    </td>
                </tr>
            </table>
            <div class="apnSwitch">
                <el-button id="applyButton" type="primary" round @click="applyAPN">{{ $t('common.applyButton') }}</el-button>
            </div>
            <!-- APN编辑对话框 -->
            <confirmDialog id="apnSettingDialog" ref="editDialogRef" :title="editForm.label.toUpperCase()" @confirm="editConfirm" @cancel="editCancel">
                <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-position="top">
                    <el-link v-if="editForm.label === 'apn1'" type="primary" :underline="false" @click="useDefault">{{ $t('netWork.apnSettings.useDefaultConfig') }}</el-link>
                    <el-form-item prop="name" :label="$t('netWork.apnSettings.apnAPN')">
                        <el-input id="name_edit" v-model.trim="editForm.name" maxLength="57"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('netWork.apnSettings.Status')" prop="switchStatus">
                        <el-switch id="switch_edit" v-model="editForm.switchStatus"></el-switch>
                    </el-form-item>

                    <div v-if="!isNoneAuth">
                        <el-form-item :label="$t('common.username')" prop="username">
                            <el-input id="username_edit" v-model.trim="editForm.username" maxLength="63"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('common.password')" prop="password">
                            <el-input id="password" :type="isShowPassword ? 'password' : 'text'" v-model.trim="editForm.password" maxLength="63">
                                <i id="passwordIcon" slot="suffix" :class="isShowPassword ? 'el-icon-my-eye-hide' : 'el-icon-my-eye-reveal'" @click="showPass"></i>
                            </el-input>
                        </el-form-item>
                    </div>
                    <el-form-item :label="$t('netWork.apnSettings.apnAuthenticationType')" prop="authType">
                        <el-select id="authTypeSelect" v-model="editForm.authType">
                            <div id="authTypeOptions">
                                <el-option :value="authItem.value" :label="authItem.label" v-for="authItem in getAuthTypeOptions" :key="authItem.value"></el-option>
                            </div>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="$t('security.accessControl.protocol')" prop="pdnType">
                        <el-select id="protocolTypeSelect" v-model="editForm.pdnType">
                            <div id="protocolTypeOptions">
                                <el-option :value="pdnItem.value" :label="pdnItem.label" v-for="pdnItem in apnOptions" :key="pdnItem.value"></el-option>
                            </div>
                        </el-select>
                    </el-form-item>
                </el-form>
            </confirmDialog>
        </div>

        <confirmDialog ref="countdownRef" :count="10">
            <span>{{ $t('netWork.wanSettings.waitSettingMsg') }}</span>
        </confirmDialog>
    </div>
</template>

<script>
import { REGULAR_RULES } from '@/constant/regularRules';
import { errorCode } from '@/constant/dict';
import { hasDuplicateItem } from '@/utils/common';
import { getByteLength } from '@/utils/common';
import { mapState, mapActions } from 'vuex';
import { getProfileInfo,updateProfileInfoById,getInternetInfo,setDefalutApn } from '@/api/mobile';

export default {
    inject: ['reload'],
    data() {
        const nameValid = (rule, value, callback) => {
            if (!value) {
                return callback(new Error(this.$t('errorTips.cannotBeEmpty')));
            }
            if (getByteLength(value) > 57) {
                return callback(new Error(this.$t('errorTips.maxLength')));
            } else {
                if (REGULAR_RULES.LETTER_OR_NUMBER_OR_POINT_HYPHEN.test(value)) {
                    if (REGULAR_RULES.START_END_MUST_LETTER_OR_NUMBER.test(value)) {
                        callback();
                    } else {
                        callback(new Error(this.$t('errorTips.startAndEndMustLetterOrNumber')));
                    }
                } else {
                    callback(new Error(this.$t('errorTips.inputValidatorTips')));
                }
            }
        };

        const usernameValid = (rule, value, callback) => {
            if (!value) {
                return callback(new Error(this.$t('errorTips.cannotBeEmpty')));
            }
            if (value) {
                const result = this.$nameCheck(value, 63);
                if (result == errorCode.BYTEERR) {
                    callback(new Error(this.$t('errorTips.maxLength')));
                } else if (!result) {
                    callback(new Error(this.$t('netWork.wanSettings.illegalDataTitle')));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };

        const passwordValid = (rule, value, callback) => {
            if (!value) {
                return callback(new Error(this.$t('errorTips.cannotBeEmpty')));
            }
            if (value) {
                const result = this.$checkStr(value, false, true, true, false, 63, 33);
                if (result == errorCode.BYTEERR) {
                    callback(new Error(this.$t('errorTips.maxLength')));
                } else if (result == errorCode.STRERR || result == errorCode.ACCIIERR) {
                    callback(new Error(this.$t('netWork.wanSettings.illegalDataTitle')));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };
        return {
            defaultConfig: '',
            defaultId: '1', // 默认第一条defalut
            apnListInfos: [],
            initList: [], // 初始化数据
            formatList: [], // 格式化后的页面数据
            isShowPassword: true, // 是否显示密码
            currentApn: {}, // 当前修改的数据
            editForm: {
                label: '',
                password: '',
                name: '',
                username: '',
                authType: '',
                pdptype: '',
                switchStatus: false
            },
            authOptions: [
                {
                    value: '0',
                    label: 'NONE'
                },
                {
                    value: '1',
                    label: 'PAP'
                },
                {
                    value: '2',
                    label: 'CHAP'
                }
            ],
            apnOptions: [
                {
                    value: '0',
                    label: 'IPv4'
                },
                {
                    value: '1',
                    label: 'IPv6'
                },
                {
                    value: '2',
                    label: 'IPv4v6'
                }
            ],
            editFormRules: {
                name: [{ validator: nameValid, trigger: 'blur' }],
                username: [{ validator: usernameValid, trigger: ['blur', 'change'], required: !this.isNoneAuth }],
                password: [{ validator: passwordValid, trigger: ['blur', 'change'], required: !this.isNoneAuth }]
            },
        };
    },
    methods: {
        ...mapActions('firmware', ['FETCHNATIPPT']),

        checkNameRepeat() {
            console.log("",this.formatList)
            const res = hasDuplicateItem(this.formatList, this.editForm, 'name', this.currentApn);
            return res;
        },
        /**
         * 获取默认的APN信息
         */
        async getDefaultApnConfig() {
            //todo
            // 获取 default 数据节点：apnname,username,password,protocol,auth_type
            const profileInfo = await getProfileInfo()().catch((err) => {
                console.log(err);
            });
            if (profileInfo) {
                this.defaultConfig = profileInfo;
            }
        },
        // 数据初始化
        async getApnInfo() {
            this.formatList = [];
            const profileInfo = await getProfileInfo().catch((err) => {
                console.log(err);
            });
            this.defaultId = profileInfo.select_profile_id;
            this.apnListInfos = profileInfo.mIspProfileList;
            console.log("profileInfo...",profileInfo );
            if (Array.isArray(this.apnListInfos) && this.apnListInfos.length) {
                console.log("render...");
                this.render();
            }
        },
        render() {
             console.log("rendering", )
            if (!this.formatList.length) {
                this.apnListInfos.forEach((apnItem) => {
                    this.formatList.push({
                        id: apnItem.profile_id,
                        enable: true,
                        label: apnItem.profile_name,//例：CMNET
                        name: apnItem.profile_apn,  //例：cmnet
                        authType: apnItem.profile_type,
                        username: apnItem.username,
                        password:apnItem.password,
                        switchStatus: true,
                        isChecked: apnItem.profile_id == this.defaultId
                    });
                });
            }
           console.log("isArray:",Array.isArray(this.formatList))
            console.log("apnListInfos:",)
        },

        // 修改复选框
        changeDefault(currentIndex) {
            this.formatList.forEach((e, i) => {
                if (currentIndex === i) {
                    e.isChecked = true;
                } else {
                    e.isChecked = false;
                }
            });
        },
        async editDialog(item) {
            this.$refs.editDialogRef.show();
            this.currentApn = item;
            this.editForm = { ...this.currentApn };
        },

        async useDefault() {
            this.editForm = { ...this.currentApn, ...this.getDefaultConfig };
        },

        // 编辑点击确认
        editConfirm() {
            this.$refs.editFormRef.validate(async (valid) => {
                if (valid) {
                    if (this.checkNameRepeat()) {
                        return this.$message.error(this.$t('errorTips.nameExist'));
                    }
                    this.$refs.editDialogRef.banConfirm();
                    let { id, isChecked, label, switchStatus, username, authType, name, password, pdnType, manageInterface, mac, vId, mtu, ippt } = this.editForm;
                   
                    
                    if (authType == '0') {
                        username = '';
                        password = '';
                    }
                    console.log(this.editForm);
                    const res = await updateProfileInfoById(this.editForm).catch((err) => {
                        console.log(err);
                    });


                    if (res && res.result === 'success') {
                        this.$message.success(this.$t('common.success'));
                        
                        if (authType == '0') {
                            this.editForm.username = '';
                            this.editForm.password = '';
                        }
                        this.$set(this.formatList, +id - 1, this.editForm);
                        this.isShowPassword = true;
                        this.$refs.editDialogRef.hide();
                    } else {
                        this.$message.error(this.$t('common.error'));
                    }
                    setTimeout(() => {
                        this.$refs.editDialogRef.cancelBanConfirm();
                    }, 2000);
                }
            });
        },

        async setApnListStrNode() {
            this.formatList.forEach(async (item) => {
                const params = { 
                    profile_id:`${item.id}`,
                    enable:`${item.enable}`,
                    label:`${item.label}`,
                    name:`${item.name}`,
                    auth_type:`${item.authType}`,
                    username:`${item.username}`,
                    password:`${item.password}`,
                    pdn_type:`${item.pdpType}`
                 };
                await this.updateProfileInfoById(params);
            });
        },

        editCancel() {
            this.$refs.editDialogRef.hide();
            this.isShowPassword = true;
            // this.getApnInfo();
        },

        async setDefalut() {
            // 设置 defalut 接口
            
            let val = '1';
            this.formatList.forEach((item, index) => {
                if (item.isChecked) {
                    val = index + 1 + '';
                }
            });
            await setDefalutApn({default_id:val});
        },

        // 获取 mobileConnection 状态
        async getMobileConnection() {
            const res = await getInternetInfo().catch((err) => {
                console.log(err);
            });
            if (res.internet.select_mode) {
                // this.$message.success(this.$t('common.success'));
                this.$refs.countdownRef.show();
                this.$refs.countdownRef.changeDialogStyle();
            } else {
                this.$message.error(this.$t('common.error'));
            }
        },

        async applyAPN() {
            this.setDefalut();
            this.getMobileConnection();
        },

        showPass() {
            this.isShowPassword = !this.isShowPassword;
        },

        jumpBackUrl() {
            this.$router.push('/netWork/mobileSettings');
        }
    },
    created() {
        this.getApnInfo();
        // 只有 Humax 需要获取默认 APN 的 配置
        if (this.isHumax) {
            this.getDefaultApnConfig();
        }
    },
    computed: {
        getDefaultConfig() {
            const defaultInfo = this.defaultConfig.split(',').map((item) => item);
            return {
                name: defaultInfo[0],
                username: defaultInfo[1],
                password: defaultInfo[2],
                pdnType: defaultInfo[3] || '2',
                authType: defaultInfo[4] || '3'
            };
        },
        getAuthTypeOptions() {
            const data = this.authOptions;
            return data;
        },
        isNoneAuth() {
            return this.editForm.authType === '0';
        },

        isHumax() {
            return false;
        }
    }
};
</script>
<style lang="less" scoped>
@import '@/assets/css/theme_blue/component_common.less';
@import '@/assets/css/theme_blue/component_round.less';
@import '@/assets/css/theme_blue/style.less';
.checkbox {
    zoom: 150%;
}
table td {
    vertical-align: middle !important;
}
.clamp-ellipsis {
    max-width: 200px;
    overflow: hidden;
    word-wrap: break-word;
    text-align: center;
    padding: 6px;
}

#apnSettingDialog {
    font-weight: bold;
    /deep/ .el-dialog__body {
        padding: 10px 20px 0px;
    }
    /deep/ .el-input__inner {
        font-weight: bold;
    }
    /deep/ .el-form-item__error {
        font-weight: normal;
        white-space: normal;
    }
}
.defaultApnInfo {
    margin-bottom: 12px;
}
</style>
